import modelExtend from 'dva-model-extend'
import {query, gather, queryDetail} from 'services/tai'
import {pageModel} from 'models/common'
import queryString from 'query-string'

export default modelExtend(pageModel, {

  namespace: 'taiList',

  state: {
    detail: null,
    styleType: 1,
    modelVisable: false
  },

  reducers: {
    gatheredSuccess(state, {payload}) {
      let {gathered, id} = payload
      state.data.list = state.data.list.map(item => {
        return {
          ...item,
          gathered: item._id === id ? gathered : item.gathered
        }
      })
      return { ...state };
    },

    updateDetail(state, {payload}) {
      return { ...state, ...payload };
    },

    updateState(state, {payload}) {
      return { ...state, ...payload };
    },
  },

  subscriptions: {
    setup({dispatch, history}) {
      history.listen((location) => {
        if (location.pathname === '/tai') {
          dispatch({
            type: 'query',
            payload: {
              type: location.query ? location.query.type : '1',
              regions: location.query ? location.query.regions : '',
              ...queryString.parse(location.search),
            }
          })
        }
      })
    },
  },

  effects: {
    * query({payload}, {call, put}) {
      const data = yield call(query, payload)
      if (data.code === 200) {
        yield put({
          type: 'querySuccess',
          payload: {
            data: data.data,
            pagination: {
              current: Number(payload.page) || 1,
              pageSize: Number(payload.pageSize) || 1000,
              total: data.data.list.total,
            },
          },
        })
      } else {
        throw data
      }
    },

    * queryDetail({payload}, {call, put}) {
      const data = yield call(queryDetail, payload)
      if (data.code === 200) {


        let transData = data.data

        // let x = yield tjs.translate('test')
        // transData['x'] = x.result[0]
        yield put({
          type: 'updateDetail',
          payload: {
            detail: transData
          }
        })



      } else {
        throw data
      }
    },

    * gather({payload}, {call, put}) {
      const data = yield call(gather, payload)
      if (data.code === 1) {
        yield put({
          type: 'gatheredSuccess',
          payload,
        })
      } else {
        throw data
      }
    },
  },
})
